package com.iss.yunpan.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iss.yunpan.entity.FileContent;
import com.iss.yunpan.service.FileService;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;
import java.io.IOException;

@Controller
public class FileController {
    @Autowired
    private FileService service;

    @RequestMapping("getAllFile")
    @ResponseBody
    public Map<String, Object> getAllFile(String id, int page, int limit, String parentId) {
        System.out.println(id);
        if (parentId == null) {
            parentId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(page, limit);
        List<FileContent> list = service.getAllFile(id, parentId);
        PageInfo<FileContent> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        map.put("code", 0);
        map.put("msg", "");
        map.put("patentId", parentId);
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @RequestMapping("getAllShare")
    @ResponseBody
    public Map<String, Object> getAllShare(String id, int page, int limit, String parentId) {
        System.out.println(id);
        if (parentId == null) {
            parentId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(page, limit);
        List<FileContent> list = service.getAllShare(id, parentId);
        PageInfo<FileContent> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        map.put("code", 0);
        map.put("msg", "");
        map.put("patentId", parentId);
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @RequestMapping("getAllCollect")
    @ResponseBody
    public Map<String, Object> getAllCollect(String id, int page, int limit, String parentId) {
        System.out.println(id);
        if (parentId == null) {
            parentId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(page, limit);
        List<FileContent> list = service.getAllCollect(id, parentId);
        PageInfo<FileContent> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        map.put("code", 0);
        map.put("msg", "");
        map.put("patentId", parentId);
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }

    @RequestMapping("getAllTrash")
    @ResponseBody
    public Map<String, Object> getAllTrash(String id, int page, int limit, String parentId) {
        System.out.println(id);
        if (parentId == null) {
            parentId = "0";
        }
        Map<String, Object> map = new HashMap<>();
        PageHelper.startPage(page, limit);
        List<FileContent> list = service.getAllTrash(id, parentId);
        PageInfo<FileContent> pageInfo = new PageInfo<>(list);
        System.out.println(pageInfo);
        map.put("code", 0);
        map.put("msg", "");
        map.put("patentId", parentId);
        map.put("count", pageInfo.getTotal());
        map.put("data", pageInfo.getList());
        return map;
    }


    @RequestMapping("uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(@RequestParam("file") MultipartFile file, String parentId) throws IOException {
        Map<String, Object> map = new HashMap<>();
        if (parentId == null) {
            parentId = "0";
        }
        if (file != null) {
            String fileName = file.getOriginalFilename();
            InputStream input = file.getInputStream();
            service.uploadFile(fileName, input, parentId);
            map.put("code", 0);
            map.put("msg", "上传成功");
        } else {
            map.put("msg", "文件不能为空");
        }
        return map;
    }

    @RequestMapping("insertFloder")
    @ResponseBody
    public Map<String, Object> insertFloder(String fileName, Integer parentId) {
        Map<String, Object> map = new HashMap<>();
        if (parentId == null) {
            parentId = 0;
        }
        if (fileName.equals("")) {
            map.put("msg", "文件夹不能为空");
        } else {
            boolean flag = service.checkFileContent(fileName, parentId);
            if (flag)
                map.put("msg", "文件夹名字不能重复");
            else {
                service.insertFloder(fileName, parentId);
                map.put("code", 0);
                map.put("msg", "文件夹新建成功");
            }
        }
        return map;
    }

    @ResponseBody
    @RequestMapping("download")
    public ResponseEntity<byte[]> download(String fileAbsolute, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String downLoadPath = request.getServletContext().getRealPath("uploadfiles");
        // 设置下载文件使用的报头
        response.setHeader("Content-Type", "application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + toUTF8String(fileAbsolute));
        byte[] newByte = service.download(fileAbsolute);
        return new ResponseEntity<byte[]>(newByte, HttpStatus.OK);
    }

    /**
     * 下载保存时中文文件名的字符编码转换方法
     */
    public String toUTF8String(String str) {
        StringBuffer sb = new StringBuffer();
        int len = str.length();
        for (int i = 0; i < len; i++) {
            // 取出字符中的每个字符
            char c = str.charAt(i);
            // Unicode 码值为 0 ～ 255 时，不做处理
            if (c >= 0 && c <= 255) {
                sb.append(c);
            } else {
                // 转换 UTF-8 编码
                byte b[];
                try {
                    b = Character.toString(c).getBytes("UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                    b = null;
                }
                // 转换为%HH的字符串形式
                for (int j = 0; j < b.length; j++) {
                    int k = b[j];
                    if (k < 0) {
                        k &= 255;
                    }
                    sb.append("%" + Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }

    @RequestMapping("getFile")
    @ResponseBody
    public Map<String, String> getFile(String fileAbsolute) {
        String url = service.getFile(fileAbsolute);
        Map<String, String> map = new HashMap<>();
        map.put("url", url);
        return map;
    }

    @RequestMapping("getUrl")
    @ResponseBody
    public String getUrl(String fileAbsolute) {
        String url = service.getFile(fileAbsolute);
        return url;
    }

    @RequestMapping("share")
    @ResponseBody
    public void share(String fileAbsolute) {
        service.share(fileAbsolute);
    }

    @RequestMapping("deleteShare")
    @ResponseBody
    public void deleteShare(String fileAbsolute) {
        service.deleteShare(fileAbsolute);
    }

    @RequestMapping("collect")
    @ResponseBody
    public void collect(String fileAbsolute) {
        service.collect(fileAbsolute);
    }

    @RequestMapping("deleteCollect")
    @ResponseBody
    public void deleteCollect(String fileAbsolute) {
        service.deleteCollect(fileAbsolute);
    }

    @RequestMapping("trash")
    @ResponseBody
    public void trash(String fileAbsolute) {
        service.trash(fileAbsolute);
    }

    @RequestMapping("deleteTrash")
    @ResponseBody
    public void deleteTrash(String fileAbsolute) {
        service.deleteTrash(fileAbsolute);
    }

    @RequestMapping("deleteComplete")
    @ResponseBody//空跳转
    public Map<String, Object> deleteComplete(String fileName, Integer parentId) throws IOException {//map为springmvc上传内容类型,获取上传文件file信息，“file”为底层所传
        Map<String, Object> map = new HashMap<>();
        service.deleteComplete(fileName);
        map.put("code", 0);
        map.put("msg", "彻底删除成功");
        return map;
    }

    @RequestMapping("rename")
    @ResponseBody
    public void rename(String oldName, String newName) {
        service.rename(oldName, newName);
    }

    @RequestMapping("copyFile")
    public String copyFile(String orignPath, String newPath) {
        service.copyFile(orignPath, newPath);
        return "file/fileList";


    }
}


